package juc;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author fangbin
 * @desc 读写锁，排他锁与共享锁
 * @date 2020/6/10 22:39
 */
public class ReadWriteDemo {

    public static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    public  static ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

    public  static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void read(){
        readLock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"获取读锁");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            readLock.unlock();

        }
    }
    public static void write(){
        writeLock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"获取写锁");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            writeLock.unlock();

        }
    }

    public static void main(String[] args) {

        ReadWriteDemo readWriteDemo = new ReadWriteDemo();


        new Thread(new Runnable() {
            @Override
            public void run() {
                write();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                read();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                read();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                write();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                read();
            }
        }).start();
    }


}
